package com.efuture.jdbc;

import java.io.BufferedReader;
import java.io.FileReader;
import java.net.URL;
import java.sql.*;
import java.util.Properties;

/**
 * @ClassNAME JDBCUtils
 * @Description JDBC工具类的编写
 * @Author zhaoshanshan
 * @Date 2021/9/19 8:22 下午
 * @Version 1.0
 */
public class JDBCUtils {

    public static String url;
    public static String userName;
    public static String passWord;
    public static String driver;
    static {
        try{
            //加载文件
            ClassLoader classLoader = JDBCUtils.class.getClassLoader();
            URL res = classLoader.getResource("jdbc.properties");//该种方式路径不能有中文，如果有，将找不到路径
            String path =  res.getPath();
            System.out.println("path:"+path);
            Properties properties = new Properties();
            BufferedReader br = new BufferedReader(new FileReader(path));
            properties.load(br);
           url = properties.getProperty("url");
           userName = properties.getProperty("userName");
           passWord = properties.getProperty("passWord");
           driver = properties.getProperty("driver");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //获取连接
    public static Connection getConnection() {
        try{
            return DriverManager.getConnection(url,userName,passWord);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
    //关闭资源
    public static void close(Connection conn, Statement stmt){
        if(null!=conn){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(null!=stmt){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
    public static void close(ResultSet rst, Connection conn, Statement stmt){
        if(null!=rst){
            try {
                rst.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(null!=conn){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(null!=stmt){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }


}